//
//  OtherPersonalViewController.m
//  项目三
//
//  Created by rimi1 on 2016/12/11.
//  Copyright © 2016年 Wangxingqian. All rights reserved.
//

#import "OtherPersonalViewController.h"
#import "SignInViewController.h"// 登录界面
#import "PersonalFCViewController.h"// 关注和粉丝
#import "CommentViewController.h"// 个人作品详情界面
#import "DetailViewController.h"// 系统详情界面

#import "PersonalHeadView.h"// 头部视图
#import "MenuListTableViewCell.h"// cell
#import "Alert.h"

#import "AVRequest+Relation.h"
#import "AVRequest+FC.h"

@interface OtherPersonalViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) PersonalHeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <AVObject *> *menuArr;
@property (nonatomic, strong) NSMutableArray <AVObject *> *collectArr;

@end

@implementation OtherPersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeAppearance];
}

#pragma mark - initialize

- (void)initializeDataSource {
    self.menuArr = [NSMutableArray array];
    self.collectArr = [NSMutableArray array];
    [self urlDynamicRequest];
    [self urlCollectRequest];
    
    if ([MyUser sharedUser].isSignIn) {
        [self signInSucceed];
    }else {
        [self.navigationBar.right setTitle:@"关注" forState:UIControlStateNormal];
    }
}

- (void)initializeAppearance {
    self.navigationBar.title.text = @"个人中心";
    self.navigationBar.right.frame = CGRectMake(kWIDTH - 10 - 88, 20, 88, 44);
    [self initHead];
    [self.headView signInWithIs:YES];
    [self.headView.myMenu setTitle:@"个人作品" forState:UIControlStateNormal];
    
    self.tableView.tableHeaderView = self.headView;
    [self.view addSubview:self.tableView];
}

- (void)initHead {
    [self.headView fcAssignmentWithFansCount:self.obj[@"fansCount"] concernCount:self.obj[@"concernCount"]];
    self.headView.name.text = self.obj[@"name"];
    
    NSURL *url = [NSURL URLWithString:self.obj[@"headImage"]];
    [self.headView.headImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"个人"] options:SDWebImageProgressiveDownload];
}

#pragma mark - URLRquest
// 个人作品
- (void)urlDynamicRequest {
    [AVRequest avDynamicWithObj:self.obj query:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        
        for (NSInteger i = objects.count - 1; i >= 0; i--) {
            [self.menuArr addObject:objects[i]];
        }
        [self.tableView reloadData];
    }];
}
// 收藏
- (void)urlCollectRequest {
    [AVRequest avCollcetWithObj:self.obj query:^(NSArray *objects, NSError *error) {
        if (error) {
            return;
        }
        
        for (NSInteger i = objects.count - 1; i >= 0; i--) {
            [self.collectArr addObject:objects[i]];
        }
        [self.tableView reloadData];
    }];
}
// 是否已关注
- (void)urlIsConcern {
    [AVRequest avIsConcernWithObjId:self.obj.objectId succeed:^(BOOL succeed, NSError *error) {
        if (error) {
            [self.navigationBar.right removeFromSuperview];
            return;
        }
        
        NSString *str;
        // 真为已关注
        if (succeed) {
            str = @"取消关注";
        }else {
            str = @"关注";
        }
        [self.navigationBar.right setTitle:str forState:UIControlStateNormal];
    }];
}
// 删除关注
- (void)urlRemoveConcern {
    AVObject *obj = [AVObject objectWithClassName:@"MyUser" objectId:[MyUser sharedUser].userId];
    NSInteger count = [[MyUser sharedUser].concernCount integerValue] - 1;
    NSString *countStr = [NSString stringWithFormat:@"%ld", count];
    [obj setObject:countStr forKey:@"concernCount"];
    
    [AVRequest avRemoveConcernWithObj:obj removeObj:self.obj saveSucceed:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"取消失败" message:nil];
            return;
        }
        
        if (succeed) {
            [self.navigationBar.right setTitle:@"关注" forState:UIControlStateNormal];
            [MyUser sharedUser].concernCount = countStr;
            self.headView.fans.count.text = self.obj[@"fansCount"];
        }else {
            [Alert alertWithTitle:@"取消失败" message:nil];
        }
    }];
}
// 添加关注
- (void)urlAddConcern {
    AVObject *obj = [AVObject objectWithClassName:@"MyUser" objectId:[MyUser sharedUser].userId];
    NSInteger count = [[MyUser sharedUser].concernCount integerValue] + 1;
    NSString *countStr = [NSString stringWithFormat:@"%ld", count];
    [obj setObject:countStr forKey:@"concernCount"];
    
    [AVRequest avAddConcernWithObj:obj addObj:self.obj saveSucceed:^(BOOL succeed, NSError *error) {
        if (error) {
            [Alert alertWithTitle:@"关注失败" message:nil];
            return;
        }
        
        if (succeed) {
            [self.navigationBar.right setTitle:@"取消关注" forState:UIControlStateNormal];
            [MyUser sharedUser].concernCount = countStr;
            self.headView.fans.count.text = self.obj[@"fansCount"];
        }else {
            [Alert alertWithTitle:@"关注失败" message:nil];
        }
    }];
}

#pragma mark - Custom Method

- (void)signInSucceed {
    // 判断是否是点击进自己
    if ([self.obj.objectId isEqualToString:[MyUser sharedUser].userId]) {
        [self.navigationBar.right removeFromSuperview];
    }else {
        [self urlIsConcern];
    }
}

// 点击个人作品时，跳转
- (void)tapPersonalCellWithObj:(AVObject *)obj {
    CommentViewController *comment = [[CommentViewController alloc] init];
    comment.obj = obj;
    [self.navigationController pushViewController:comment animated:YES];
}

#pragma mark - respondsTo..

- (void)respondsToRight:(UIButton *)sender {
    if ([MyUser sharedUser].isSignIn) {
        if ([sender.titleLabel.text isEqualToString:@"取消关注"]) {
            [self urlRemoveConcern];
        }else {
            [self urlAddConcern];
        }
    }else {
        SignInViewController *signIn = [[SignInViewController alloc] init];
        [self.navigationController pushViewController:signIn animated:YES];
    }
    
}
// 100：粉丝  101：关注  102：菜谱  103：收藏
- (void)respondsToButton:(UIButton *)sender {
    NSInteger tag = sender.tag;
    if (tag == 100 || tag == 101) {
        BOOL isFC;
        if (tag == 100) {
            isFC = NO;
        }else {
            isFC = YES;
        }
        
        PersonalFCViewController *fc = [[PersonalFCViewController alloc] init];
        fc.obj = self.obj;
        fc.isSelf = NO;
        fc.isFC = isFC;
        [self.navigationController pushViewController:fc animated:YES];
        
    }else if (tag == 102) {
        sender.selected = YES;
        self.headView.myCollect.selected = NO;
        [self.tableView reloadData];
    }else if (tag == 103) {
        sender.selected = YES;
        self.headView.myMenu.selected = NO;
        [self.tableView reloadData];
    }
}

- (void)respondsToSignIn:(UIButton *)sender {
    SignInViewController *signIn = [[SignInViewController alloc] init];
    
    __weak OtherPersonalViewController *personal = self;
    signIn.signInSucceed = ^() {
        [personal urlDynamicRequest];
        [personal urlCollectRequest];
    };
    [self.navigationController pushViewController:signIn animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.headView.myMenu.selected) {
        return self.menuArr.count;
    }else {
        return self.collectArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusing = @"PersonalTableViewCell";
    MenuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusing];
    if (!cell) {
        cell = [[MenuListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusing];
    }
    AVObject *obj;
    if (self.headView.myMenu.selected) {
        obj = self.menuArr[indexPath.row];
    }else {
        obj = self.collectArr[indexPath.row];
    }
    
    NSURL *url = [NSURL URLWithString:obj[@"img"]];
    [cell.imageViewList sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"默认加载图"] options:SDWebImageProgressiveDownload];
    cell.name.text = obj[@"name"];
    cell.food.text = obj[@"food"];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UITableViewDelgeatae

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AVObject *obj;
    if (self.headView.myMenu.selected) {
        obj = self.menuArr[indexPath.row];
        [self tapPersonalCellWithObj:obj];
    }else {
        obj = self.collectArr[indexPath.row];
        // 存在为个人作品，不存在则是系统菜谱
        if (obj[@"dynamic"]) {
            [self tapPersonalCellWithObj:obj[@"dynamic"]];
        }else {
            DetailViewController *detai = [[DetailViewController alloc] init];
            detai.menuId = obj[@"id"];
            [self.navigationController pushViewController:detai animated:YES];
            
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return WXQAdaptionHeight(115);
}

#pragma mark - get

- (PersonalHeadView *)headView {
    
    if (!_headView) {
        
        _headView = [[PersonalHeadView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, WXQAdaptionHeight(210))];
        
        __weak OtherPersonalViewController *personal = self;
        _headView.tapButton = ^(UIButton *sender) {
            [personal respondsToButton:sender];
        };
        _headView.tapSignIn = ^(UIButton *sender) {
            [personal respondsToSignIn:sender];
        };
        
    }
    return _headView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWIDTH, kHEIGHT - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.bounces = NO;
        
    }
    return _tableView;
}

@end















